<template>
    <div class="min-h-screen bg-gray-100 p-6">
        <div class="bg-white rounded-lg shadow p-6">
            <div class="flex justify-between items-center mb-6">
                <h1 class="text-2xl font-bold">新闻标签管理</h1>
                <n-button type="primary" @click="showAddModal = true">
                    <template #icon>
                        <n-icon><AddOutline /></n-icon>
                    </template>
                    添加标签
                </n-button>
            </div>

            <!-- 搜索区域 -->
            <div class="mb-4 flex gap-4">
                <n-input v-model:value="searchKeyword" placeholder="请输入标签名称搜索" class="w-64" />
                <n-button type="primary" @click="handleSearch">搜索</n-button>
                <n-button @click="resetSearch">重置</n-button>
            </div>

            <!-- 表格区域 -->
            <n-data-table
                :columns="columns"
                :data="filteredTags"
                :pagination="pagination"
                @update:page="handlePageChange"
                @update:page-size="handlePageSizeChange"
            />
        </div>

        <!-- 添加/编辑标签弹窗 -->
        <n-modal v-model:show="showAddModal" preset="card" :title="isEdit ? '编辑标签' : '添加标签'">
            <n-form
                ref="formRef"
                :model="tagForm"
                :rules="rules"
                label-placement="left"
                label-width="100"
                require-mark-placement="right-hanging"
            >
                <n-form-item label="标签名称" path="name">
                    <n-input v-model:value="tagForm.name" placeholder="请输入标签名称" />
                </n-form-item>
                <n-form-item label="标签描述" path="description">
                    <n-input
                        v-model:value="tagForm.description"
                        type="textarea"
                        placeholder="请输入标签描述"
                    />
                </n-form-item>
                <n-form-item label="标签颜色" path="color">
                    <n-color-picker v-model:value="tagForm.color" />
                </n-form-item>
            </n-form>
            <template #footer>
                <div class="flex justify-end gap-4">
                    <n-button @click="showAddModal = false">取消</n-button>
                    <n-button type="primary" @click="handleSubmit">确定</n-button>
                </div>
            </template>
        </n-modal>

        <!-- 删除确认弹窗 -->
        <n-modal v-model:show="showDeleteModal" preset="dialog" type="warning">
            <template #header>
                确认删除
            </template>
            <div>
                确定要删除标签 "{{ tagToDelete?.name }}" 吗？此操作不可恢复。
            </div>
            <template #action>
                <div class="flex justify-end gap-4">
                    <n-button @click="showDeleteModal = false">取消</n-button>
                    <n-button type="error" @click="confirmDelete">删除</n-button>
                </div>
            </template>
        </n-modal>
    </div>
</template>

<script setup lang="ts">
import { ref, computed, h } from 'vue';
import { AddOutline, CreateOutline, TrashOutline } from '@vicons/ionicons5';
import { useMessage, NButton } from 'naive-ui';

// 定义标签类型
interface Tag {
    id: number;
    name: string;
    description: string;
    color: string;
    createTime: string;
}

// 表单规则
const rules = {
    name: {
        required: true,
        message: '请输入标签名称',
        trigger: 'blur'
    },
    description: {
        required: true,
        message: '请输入标签描述',
        trigger: 'blur'
    },
    color: {
        required: true,
        message: '请选择标签颜色',
        trigger: 'change'
    }
};

// 状态变量
const message = useMessage();
const searchKeyword = ref('');
const showAddModal = ref(false);
const showDeleteModal = ref(false);
const isEdit = ref(false);
const tagToDelete = ref<Tag | null>(null);
const formRef = ref(null);

// 分页配置
const pagination = ref({
    page: 1,
    pageSize: 10,
    itemCount: 0,
    showSizePicker: true,
    pageSizes: [10, 20, 30, 40]
});

// 表单数据
const tagForm = ref({
    id: 0,
    name: '',
    description: '',
    color: '#18a058'
});

// 模拟数据
const tags = ref<Tag[]>([
    { id: 1, name: '科技', description: '科技相关新闻', color: '#18a058', createTime: '2024-03-31 10:00:00' },
    { id: 2, name: '体育', description: '体育相关新闻', color: '#2080f0', createTime: '2024-03-31 11:00:00' },
    { id: 3, name: '娱乐', description: '娱乐相关新闻', color: '#f0a020', createTime: '2024-03-31 12:00:00' },
]);

// 过滤后的标签数据
const filteredTags = computed(() => {
    let result = tags.value;
    if (searchKeyword.value) {
        result = result.filter(tag => 
            tag.name.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
            tag.description.toLowerCase().includes(searchKeyword.value.toLowerCase())
        );
    }
    pagination.value.itemCount = result.length;
    return result;
});

// 表格列配置
const columns = [
    { title: 'ID', key: 'id', width: 80 },
    { title: '标签名称', key: 'name' },
    { title: '描述', key: 'description' },
    { 
        title: '颜色', 
        key: 'color',
        render(row: Tag) {
            return h('div', { style: { display: 'flex', alignItems: 'center' } }, [
                h('div', { 
                    style: { 
                        width: '20px', 
                        height: '20px', 
                        backgroundColor: row.color,
                        borderRadius: '4px',
                        marginRight: '8px'
                    } 
                }),
                row.color
            ]);
        }
    },
    { title: '创建时间', key: 'createTime' },
    {
        title: '操作',
        key: 'actions',
        render(row: Tag) {
            return h('div', { style: { display: 'flex', gap: '8px' } }, [
                h(
                    NButton,
                    {
                        size: 'small',
                        type: 'primary',
                        onClick: () => handleEdit(row)
                    },
                    { default: () => '编辑' }
                ),
                h(
                    NButton,
                    {
                        size: 'small',
                        type: 'error',
                        onClick: () => handleDelete(row)
                    },
                    { default: () => '删除' }
                )
            ]);
        }
    }
];

// 搜索处理
const handleSearch = () => {
    pagination.value.page = 1;
};

const resetSearch = () => {
    searchKeyword.value = '';
    handleSearch();
};

// 分页处理
const handlePageChange = (page: number) => {
    pagination.value.page = page;
};

const handlePageSizeChange = (pageSize: number) => {
    pagination.value.pageSize = pageSize;
    pagination.value.page = 1;
};

// 编辑标签
const handleEdit = (tag: Tag) => {
    isEdit.value = true;
    tagForm.value = { ...tag };
    showAddModal.value = true;
};

// 删除标签
const handleDelete = (tag: Tag) => {
    tagToDelete.value = tag;
    showDeleteModal.value = true;
};

const confirmDelete = () => {
    if (tagToDelete.value) {
        tags.value = tags.value.filter(tag => tag.id !== tagToDelete.value?.id);
        message.success('删除成功');
        showDeleteModal.value = false;
        tagToDelete.value = null;
    }
};

// 提交表单
const handleSubmit = () => {
    formRef.value?.validate((errors: any) => {
        if (!errors) {
            if (isEdit.value) {
                // 编辑现有标签
                const index = tags.value.findIndex(tag => tag.id === tagForm.value.id);
                if (index !== -1) {
                    tags.value[index] = { ...tagForm.value };
                    message.success('编辑成功');
                }
            } else {
                // 添加新标签
                const newTag: Tag = {
                    ...tagForm.value,
                    id: tags.value.length + 1,
                    createTime: new Date().toLocaleString()
                };
                tags.value.push(newTag);
                message.success('添加成功');
            }
            showAddModal.value = false;
            resetForm();
        }
    });
};

// 重置表单
const resetForm = () => {
    tagForm.value = {
        id: 0,
        name: '',
        description: '',
        color: '#18a058'
    };
    isEdit.value = false;
};
</script>

<style scoped>
.n-button {
    margin-right: 8px;
}
</style>